package com.hnkywl.sts.service.base;

import com.hnkywl.sts.dao.base.FwpzDao;
import com.hnkywl.sts.entity.base.Fwpz;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-5-21
 * Time: 下午2:27
 * To change this template use File | Settings | File Templates.
 */
@Service
public class FwpzService {
    private FwpzDao  fwpzDao;

    @Transactional
    public String findAllFwpz(String name, String action, int pageNo, int pageSize) {
        Page<Fwpz> fwpzPage = this.fwpzDao.findFwpzList(name, action, pageNo, pageSize);
        List<Fwpz> fwpzList = fwpzPage.getResult() == null ? new ArrayList<Fwpz>() :fwpzPage.getResult();
        String fwpzJson = BaseUtils.fetchCollectionToJson(fwpzList, "id", "name", "action", "info", "linkfield");
        return "{\"total\":" + fwpzPage.getTotalCount() + ",\"rows\":[" + fwpzJson + "]}";
    }

    /**
     * 查询服务配置明细
     * @param id
     * @return
     */
    @Transactional
    public Fwpz findFwpzDetail(Long id) {
        return this.fwpzDao.get(id);
    }

    /**
     * 保存服务配置信息
     * @param fwpz
     */
    @Transactional
    public void saveFwpz(Fwpz fwpz) {
        fwpz.setDateCreated(new Date());
        fwpz.setLastUpdated(fwpz.getDateCreated());
        this.fwpzDao.save(fwpz);
    }

    /**
     * 更新服务配置信息
     * @param fwpz
     */
    @Transactional
    public void updateFwpz(Fwpz fwpz) {
        Fwpz clone = this.findFwpzDetail(fwpz.getId());
        clone = (Fwpz) ReflectionUtils.getInstance(clone, fwpz);
        clone.setLastUpdated(new Date());
        this.fwpzDao.save(clone);
    }

    /**
     * 删除服务配置信息
     * @param id
     */
    @Transactional
    public void deleteFwpz(Long id) {
        Fwpz fwpz = fwpzDao.get(id);
        fwpz.setLastUpdated(new Date());
        fwpz.setDeleted(1);
        this.fwpzDao.save(fwpz);
    }
    @Autowired
    public void setFwpzDao(FwpzDao fwpzDao) {
        this.fwpzDao = fwpzDao;
    }

    public Fwpz findByAction(String action) {
        List<Fwpz> fwpzs = this.fwpzDao.findByAction(action);
        return fwpzs.size() == 0 ? null : fwpzs.get(0);
    }
}
